package com.erb.controller.zwj.admin;

import com.erb.entity.Pager;
import com.erb.entity.Type;
import com.erb.service.zwj.ITypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 产品类型
 */
@Controller
@RequestMapping("/admin/product-type")
public class AdminTypeController {
	@Resource
	private ITypeService typeService;

	@GetMapping("/list")
	public String list(Model model,
	                   @RequestParam(required = false, defaultValue = "1") Integer currPage,
	                   @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
		Pager pager = new Pager();
		pager.currPage = currPage;
		pager.pageSize = pageSize;
		pager.page((int) typeService.findCount());

		model.addAttribute("pager", pager);
		model.addAttribute("typeList", typeService.findAll(pager));
		return "admin/type/list";
	}

	/**
	 * 保存
	 *
	 * @param type
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save")
	public Map<String, Object> save(Type type) {
		Map<String, Object> map = new HashMap<>(2);

		// 判断是否已存在相同名称，true：存在
		if (typeService.findTypeByEqName(type.getName())) {
			map.put("code", 2);
			map.put("msg", "已存在该类型名称！");
			return map;
		}

		if (typeService.saveType(type)) {
			map.put("code", 0);
			map.put("msg", "添加成功！");
		} else {
			map.put("code", 1);
			map.put("msg", "添加失败！");
		}

		return map;
	}

	/**
	 * 查询单个
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("/edit/{id}")
	public Map<String, Object> get(@PathVariable("id") Long id) {
		Map<String, Object> map = new HashMap<>(3);

		Type typeById = typeService.findTypeById(id);
		if (null != typeById) {
			map.put("code", 0);
			map.put("msg", "查询成功！");
			map.put("obj", typeById);
		} else {
			map.put("code", 1);
			map.put("msg", "查询失败！");
		}

		return map;
	}

	/**
	 * 编辑
	 *
	 * @param type
	 * @return
	 */
	@ResponseBody
	@PostMapping("/edit")
	public Map<String, Object> edit(Type type) {
		Map<String, Object> map = new HashMap<>(2);

		// 判断是否已存在相同名称，true：存在
		if (typeService.findTypeByEqName(type.getName())) {
			map.put("code", 2);
			map.put("msg", "已存在该类型名称！");
			return map;
		}

		if (typeService.editType(type)) {
			map.put("code", 0);
			map.put("msg", "修改成功！");
		} else {
			map.put("code", 1);
			map.put("msg", "修改失败！");
		}

		return map;
	}

	/**
	 * 删除类型
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@PostMapping("/remove/{id}")
	public Map<String, Object> remove(@PathVariable("id") Long id) {
		Map<String, Object> map = new HashMap<>(3);

		if (typeService.removeType(id)) {
			map.put("code", 0);
			map.put("msg", "删除成功！");
		} else {
			map.put("code", 1);
			map.put("msg", "删除失败！");
		}

		return map;
	}
}
